import { authMiddleware } from '@/lib/api';
import { clientQueryAllMenu, queryPath } from '@/services/api';
import { cookies } from 'next/headers';
import Metadata from '@/lib/metadata';
import HomeAdminPage from '@/app/[locale]/admin/home';
import ResetPage from '@/app/[locale]/reset/reset';
import { getMetadata } from '@/lib/tool';
import { Metadata as MetadataNext } from 'next';
import { createTranslator } from 'next-intl';
import { getMessages } from '@/lib/dictionaries';

export async function generateMetadata({
  params: { locale },
}: {
  params: {
    locale: string;
  };
}): Promise<MetadataNext> {
  const t = createTranslator(await getMessages(locale));
  return getMetadata({ title: t('AdminPage.managementConsole') });
}

export default async function Page({
  params = {},
  searchParams = {},
}: {
  params: {};
  searchParams: {};
}) {
  try {
    const token = authMiddleware(cookies());
    const req1 = queryPath({
      baseURL: process.env.APP_API_SERVER,
      token,
      query: {
        name: '/',
      },
    });
    const req2 = clientQueryAllMenu({
      baseURL: process.env.APP_API_SERVER,
      token,
    });

    const responses = await Promise.all([req1, req2]);
    const resp1 = await ((await responses[0]) as Response).json();
    const resp2 = await ((await responses[1]) as Response).json();

    const metadata = new Metadata();
    metadata.set('page', ['/paths', '/'], resp1.data);
    metadata.set('menus', ['/menus', '/client'], resp2.data);
    return <HomeAdminPage metadata={metadata.toString()} />;
  } catch (e) {
    return <ResetPage error={e} />;
  }
}
